package com.asynctm.android.socialnetwork.activity;

import java.util.List;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ViewFlipper;

import com.asynctm.android.R;
import com.asynctm.android.common.application.BaseActivity;
import com.asynctm.android.common.exception.DaoException;
import com.asynctm.android.common.util.AndroidUtil;
import com.asynctm.android.common.util.ApplicationUtil;
import com.asynctm.android.socialnetwork.dao.ContactDao;
import com.asynctm.android.socialnetwork.dao.FacebookDao;
import com.asynctm.android.socialnetwork.dao.TwitterDao;
import com.asynctm.android.socialnetwork.dto.ContactDto;
import com.google.inject.Inject;

/**
 * Redes sociales
 * 
 * @author rockdrigo
 */
public class SocialNetworkActivity extends BaseActivity implements
		android.view.View.OnClickListener {

	private static final String LOG_TAG = SocialNetworkActivity.class
			.getSimpleName().toString();

	private ListView listViewTweets;
	private ListView listViewContacts;

	private Button btnLike;
	private Button btnTweet;
	private Button btnMail;

	private ImageView socialBanner;

	private ViewFlipper viewFlipper;

	private ProgressDialog progressDialog;

	/** Contactos */
	private List<ContactDto> contacts;

	/** Lista de emails actual */
	private List<String> currentEmailList;

	@Inject
	private TwitterDao twitterDao;

	@Inject
	private ContactDao contactDao;

	private GetContactsAsyncTask currentGetContactsAsyncTask;
	private GetTweetsAsyncTask currentGetTweetsAsyncTask;

	/** Listener para los elementos de la lista de contactos */
	private OnItemClickListener contactListOnItemClickListener = new OnItemClickListener() {
		public void onItemClick(AdapterView<?> parent, View v, int position,
				long id) {
			currentEmailList = contacts.get(position).getEmailList();
			if (currentEmailList.isEmpty()) {
				ApplicationUtil.showAlert(SocialNetworkActivity.this,
						R.string.msg_no_contact_email);
			} else if (currentEmailList.size() == 1) {
				String uniqueEmail = currentEmailList.get(0);
				AndroidUtil.loadEmailApp(
						SocialNetworkActivity.this,
						new String[] { uniqueEmail },
						null,
						null,
						getApplicationContext().getResources()
								.getText(R.string.email_issue).toString(),
						getApplicationContext().getResources()
								.getText(R.string.email_message).toString(),
						null);
			} else if (currentEmailList.size() > 1) {
				AndroidUtil.showListDialog(SocialNetworkActivity.this,
						currentEmailList,
						getString(R.string.lbl_dialog_title_email_list),
						new OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								String emailTo = currentEmailList.get(which);
								AndroidUtil
										.loadEmailApp(
												SocialNetworkActivity.this,
												new String[] { emailTo },
												null,
												null,
												getApplicationContext()
														.getResources()
														.getText(
																R.string.email_issue)
														.toString(),
												getApplicationContext()
														.getResources()
														.getText(
																R.string.email_message)
														.toString(), null);
							}
						});
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.social_network);
		setName(LOG_TAG);

		listViewTweets = (ListView) findViewById(R.id.listViewTweets);
		listViewContacts = (ListView) findViewById(R.id.listViewContacts);

		viewFlipper = (ViewFlipper) findViewById(R.id.viewFlipperNet);

		btnLike = (Button) findViewById(R.id.likeBtn);
		btnTweet = (Button) findViewById(R.id.twBtn);
		btnMail = (Button) findViewById(R.id.mailBtn);

		socialBanner = (ImageView) findViewById(R.id.networkBanner);

		listViewContacts.setOnItemClickListener(contactListOnItemClickListener);

		btnLike.setOnClickListener(this);
		btnTweet.setOnClickListener(this);
		btnMail.setOnClickListener(this);

		currentGetTweetsAsyncTask = new GetTweetsAsyncTask();
		currentGetTweetsAsyncTask.execute(new Void[] {});

	}

	/** Hace los cambios de Servicio */
	@Override
	public void onClick(View v) {

		if (v == btnTweet) {

			socialBanner.setVisibility(View.VISIBLE);
			currentGetTweetsAsyncTask = new GetTweetsAsyncTask();
			currentGetTweetsAsyncTask.execute(new Void[] {});

			if (viewFlipper.getCurrentView().getId() == R.id.lyoSocialEmail) {

				viewFlipper.showPrevious();

			}

		} else if (v == btnMail) {

			socialBanner.setVisibility(View.GONE);
			currentGetContactsAsyncTask = new GetContactsAsyncTask();
			currentGetContactsAsyncTask.execute(new Void[] {});

			if (viewFlipper.getCurrentView().getId() == R.id.lyoSocialTwitter) {

				viewFlipper.showNext();

			}

		} else if (v == btnLike) {

			FacebookDao facebookDao = new FacebookDao(
					SocialNetworkActivity.this, "Saludos de SiVale");
			
			Log.e(LOG_TAG, "BotonFB");

			ApplicationUtil.showShareOnFacebookDialog(this, facebookDao);

		}

	}

	@Override
	protected void onPause() {
		super.onPause();

		cancelAllPendingAsyncTasks();

	}

	private void cancelAllPendingAsyncTasks() {
		if (currentGetContactsAsyncTask != null) {
			if (!currentGetContactsAsyncTask.isCancelled()) {
				currentGetContactsAsyncTask.cancel(true);
			}
		}
		if (currentGetTweetsAsyncTask != null) {
			if (!currentGetTweetsAsyncTask.isCancelled()) {
				currentGetTweetsAsyncTask.cancel(true);
			}
		}
	}

	/**
	 * Tarea asincrona para obtener la lista de tweets
	 * 
	 * @author rockdrigo
	 */
	private class GetTweetsAsyncTask extends
			AsyncTask<Void, Void, List<twitter4j.Status>> {

		private DaoException generatedException;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			progressDialog = ProgressDialog.show(SocialNetworkActivity.this,
					"", getString(R.string.msg_default_progress));
		}

		@Override
		protected List<twitter4j.Status> doInBackground(Void... params) {
			List<twitter4j.Status> result = null;
			try {
				result = twitterDao.getUserTweets("AsyncTM");
			} catch (DaoException e) {
				generatedException = e;
				Log.e(LOG_TAG, "Error al ", e);
			}
			return result;
		}

		@Override
		protected void onPostExecute(List<twitter4j.Status> result) {
			super.onPostExecute(result);
			if (generatedException != null) {
				if (!AndroidUtil.isNetworkReachable(SocialNetworkActivity.this)) {
					ApplicationUtil
							.showNetworkUnavailableDialog(SocialNetworkActivity.this);
				} else {
					ApplicationUtil
							.showServiceUnavailableDialog(SocialNetworkActivity.this);
				}
			} else if (result == null || result.isEmpty()) {
				ApplicationUtil
						.showInfoNotFoundDialog(SocialNetworkActivity.this);
			} else {
				listViewTweets.setAdapter(new TweetsListAdapter(
						SocialNetworkActivity.this, result));
			}
			progressDialog.dismiss();
		}

	}

	/**
	 * Tarea asincrona para recuperar los contactos del dispositivo
	 * 
	 * @author rockdrigo
	 */
	private class GetContactsAsyncTask extends
			AsyncTask<Void, Void, List<ContactDto>> {

		private DaoException generatedException;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			progressDialog = ProgressDialog.show(SocialNetworkActivity.this,
					"", getString(R.string.msg_default_progress));
		}

		@Override
		protected List<ContactDto> doInBackground(Void... arg0) {

			try {
				contacts = contactDao.getContactsWithPhonesAndEmails();
			} catch (DaoException e) {
				// Should not pass
				generatedException = e;
				Log.e(LOG_TAG, "Error al recuperar los contactos", e);
			}

			return contacts;
		}

		@Override
		protected void onPostExecute(List<ContactDto> result) {
			super.onPostExecute(result);

			if (generatedException != null) {
				// should not pass
			} else if (result == null || result.isEmpty()) {
				ApplicationUtil
						.showContactsNotFoundDialog(SocialNetworkActivity.this);
			} else {
				listViewContacts.setAdapter(new ContactListAdapter(
						SocialNetworkActivity.this, result));
			}
			progressDialog.dismiss();
		}

	}

}
